package com.xyongfeng.foodManagement.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.xyongfeng.foodManagement.constant.MyConstant;
import com.xyongfeng.foodManagement.domain.Permission;
import com.xyongfeng.foodManagement.mapper.PermissionMapper;
import com.xyongfeng.foodManagement.service.PermissionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author xyongfeng
 * @description 针对表【permission】的数据库操作Service实现
 * @createDate 2024-06-10 13:53:47
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission>
        implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;


    @Resource
    private Cache<Integer, List<Permission>> adminPermCache;


    @Override
    public List<Permission> getByRoleId(Integer roleId) {
        List<Permission> perms = permissionMapper.getByRoleId(roleId);
        return perms;
    }

    @Override
    public List<Permission> getByAdminId(Integer adminId) {

        List<Permission> perms = adminPermCache.getIfPresent(adminId);
        if (perms == null) {
            // perms为null，则代表缓存中未查到
            // 获取查询数据库的锁，锁标识为 roleId
            // 这里的锁主要是保证数据库与缓存操作的原子性
            String lock = MyConstant.KEY_ADMIN_PERM + adminId;
            synchronized (lock.intern()) {
                perms = adminPermCache.getIfPresent(adminId);
                if (perms == null) {
                    perms = permissionMapper.getByAdminId(adminId);
                    adminPermCache.put(adminId, perms);
                }
            }
        }

//        List<Permission> perms = permissionMapper.getByAdminId(adminId);
        return perms;
    }


}




